package com.fyzk.activity.app;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Typeface;
import android.os.Environment;
import android.os.Handler;
import android.support.multidex.MultiDexApplication;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.fyzk.activity.welcome.WelcomeActivity;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.utils.CustomUtils;
import com.fyzk.utils.LogUtil;
import com.fyzk.utils.StorageUtils;
import com.fyzk.view.ViewCallBack;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshFooter;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshFooterCreator;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshHeaderCreator;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tyjc.lottery.R;
import com.umeng.analytics.MobclickAgent;
import com.zxy.recovery.callback.RecoveryCallback;
import com.zxy.recovery.core.Recovery;

import org.xutils.x;

import java.io.File;
import java.lang.reflect.Field;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;


/**
 * 全局变量
 * <b>集成MultiDexApplication在Android4.4就不会崩溃<b/>
 */
public class App extends MultiDexApplication implements ViewCallBack.CountDownInterface {

    private static final String TAG = "App";
    public static final String CHANNEL = "App";
    public static final String BRANCH = "basic";
    public static final String COMPANYID = "rocket";

    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
//                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    private static Context instance;
    private final Timer mLottoryTimer = new Timer();// 程序倒计时

    public static final int COUNTDOWN = 0x1000;// 提醒其他页面更新时间
    /**
     * 缓存路径
     */
    private String cachePath;

    private RequestQueue requestQueue;
    private ImageLoader imageLoader;

    public static final String APP_ID = "wxef8b1916114352a7";
    private IWXAPI api;

    // 是否晒单投注
    public static boolean isBaskOrder = false;
    //字体地址，一般放置在assets/fonts目录
    String fontPath = "fonts/pingfang.ttf";
    @Override
    public void onCreate() {
        super.onCreate();
        CustomUtils.init(this);
        ViewCallBack.getInstance().AttachCountDownObj(this);
        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        LeakCanary.install(this);
        instance = getApplicationContext();
        x.Ext.init(this);
        x.Ext.setDebug(false); // 是否输出debug日志, 开启debug会影响性能.
        cachePath = getSdcardPath();
        // 异常处理
        Recovery.getInstance()
                .debug(true)
                .recoverInBackground(false)
                .recoverStack(true)
                .mainPage(WelcomeActivity.class)
                .recoverEnabled(true)
                .callback(new MyCrashCallback())
                .silent(false, Recovery.SilentMode.RESTART_AND_CLEAR)
                .skip(WelcomeActivity.class)
                .init(this);
        mLottoryTimer.schedule(mTimerTask, 1000, 1000);
        MobclickAgent.startWithConfigure(new MobclickAgent.UMAnalyticsConfig(this,
                "551e68e4fd98c5b1dc0014c2", App.getChannel()));
//        UMAnalyticsConfig(Context context, String appkey, String channelId)
        // 微信
        api = WXAPIFactory.createWXAPI(getContext(), APP_ID, true);
        api.registerApp(APP_ID);
        JPushInterface.setDebugMode(false);
        JPushInterface.init(this);
        replaceSystemDefaultFont(this, fontPath);
    }


    public void replaceSystemDefaultFont(Context context, String fontPath) {

//這里我们修改的是MoNOSPACE,是因为我们在主题里给app设置的默认字体就是monospace，设置其他的也可以
        replaceTypefaceField("monospace", createTypeface(context, fontPath));
    }
    //通过字体地址创建自定义字体
    private Typeface createTypeface(Context context, String fontPath) {
        return Typeface.createFromAsset(context.getAssets(), fontPath);
    }
    //关键--》通过修改MONOSPACE字体为自定义的字体达到修改app默认字体的目的
    private void replaceTypefaceField(String fieldName, Object value) {
        try {
            Field defaultField = Typeface.class.getDeclaredField(fieldName);
            defaultField.setAccessible(true);
            defaultField.set(null, value);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }



    static final class MyCrashCallback implements RecoveryCallback {
        @Override
        public void stackTrace(String exceptionMessage) {
            LogUtil.e("exceptionMessage:" + exceptionMessage);
        }

        @Override
        public void cause(String cause) {
            LogUtil.e("cause:" + cause);
        }

        @Override
        public void exception(String exceptionType, String throwClassName, String throwMethodName, int throwLineNumber) {
            LogUtil.e("exceptionClassName:" + exceptionType);
            LogUtil.e("throwClassName:" + throwClassName);
            LogUtil.e("throwMethodName:" + throwMethodName);
            LogUtil.e("throwLineNumber:" + throwLineNumber);
        }

        @Override
        public void throwable(Throwable throwable) {

        }
    }

    public IWXAPI getWXApi() {
        return api;
    }

    public TimerTask mTimerTask = new TimerTask() {
        @Override
        public void run() {
            appHandler.sendEmptyMessage(COUNTDOWN);
        }
    };

    Handler appHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case COUNTDOWN:
                    ViewCallBack.getInstance().countDown();
                    break;
                default:
                    break;
            }
        }

        ;

    };

    /**
     * SD卡路径
     *
     * @return String
     */
    private String getSdcardPath() {

        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {

            File cacheDir = StorageUtils.getCacheDirectory(App.this);

            if (!cacheDir.exists()) {
                cacheDir.mkdirs();
            }

            return cacheDir.getAbsolutePath();
        } else if ((new File("/mnt/sdcard2")).exists()) {
            // 特殊的手机，如中兴V955,存储卡为sdcard2
            String path = "/mnt/sdcard2/dwj/";

            File f = new File(path);
            if (!f.exists()) {
                f.mkdirs();
            }

            return path;
        } else {
            Toast.makeText(getApplicationContext(), "未检测到sd卡",
                    Toast.LENGTH_SHORT).show();
            return "";
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }

    /**
     * 获取缓存路径
     *
     * @return String
     */
    public String getCachePath() {
        return cachePath;
    }

    /**
     * Global context
     *
     * @return
     */
    public static Context getContext() {
        return instance;
    }


    /**
     * 获取版本号
     *
     * @return
     */
    public static String getVersionName() {
        PackageManager packageManager = instance.getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo(
                    instance.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return "1.3.2";
        }
    }


    /**
     * 获取setting保存的SharedPreferences名字
     *
     * @return
     */
    public static String getSettingName() {
        return instance.getPackageName() + "_preferences";
    }

    public static int getVersionCode() {

        PackageManager packageManager = instance.getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo(
                    instance.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return 1;
        }
    }

    public static String getChannel() {
        String channel = MySharedPreferences.getInstance().getChannel();
//渠道号保存到手机，更新不变动渠道号
//        try {
//            if (TextUtil.isEmpty(channel)) {
//                channel = WalleChannelReader.getChannel(getContext());
//                MySharedPreferences.getInstance().setChannel(channel);
//            }
//        } catch (Exception e) {
//            channel = "gw";
//        }
        if (channel == null || channel.equals("")) {
            channel = "gw";
        }
        return channel;
    }

//    public static String getLocalIpAddress() {
//        try {
//            for (
//                    Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
//                            .getNetworkInterfaces();
//                    networkInterfaces.hasMoreElements(); ) {
//                NetworkInterface networkInterface = networkInterfaces.nextElement();
//                for (Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
//                     inetAddresses.hasMoreElements(); ) {
//                    InetAddress inetAddress = inetAddresses.nextElement();
//                    //过滤Loopback address, Link-local address
//                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
//                        return inetAddress.getHostAddress();
//                    }
//                }
//            }
//        } catch (SocketException e) {
//        }
//        return null;
//    }

    @Override
    public void countDown() {
        AppLotteryInfos.Dlt_endTime -= 1000;
        AppLotteryInfos.Ssq_endTime -= 1000;
        AppLotteryInfos.Qxc_endTime -= 1000;
        AppLotteryInfos.Pl5_endTime -= 1000;
        AppLotteryInfos.Pl3_endTime -= 1000;
        AppLotteryInfos.Fc3d_endTime -= 1000;
        AppLotteryInfos.SD11xuan5_endTime -= 1000;
        AppLotteryInfos.GD11xuan5_endTime -= 1000;
        AppLotteryInfos.XJ11xuan5_endTime -= 1000;
        AppLotteryInfos.GpSSC_endTime -= 1000;
        AppLotteryInfos.KLSF_endTime -= 1000;
        AppLotteryInfos.GDKLSF_endTime -= 1000;
        AppLotteryInfos.JSK3_endTime -= 1000;
        AppLotteryInfos.JLK3_endTime -= 1000;
        AppLotteryInfos.AnHuiK3_endTime -= 1000;
        AppLotteryInfos.GXK3_endTime -= 1000;
        AppLotteryInfos.KLPK_endTime -= 1000;
    }

}
